package com.tapstitch.scm.common.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class JsonUtil {

    private static Logger logger = LoggerFactory.getLogger(JsonUtil.class);

    public static String toJSONString(Object object) {
        ObjectMapper mapper = new ObjectMapper();
        //  不序列化 null 值
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        try {
            return mapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            logger.error("序列化json出错", e);
            throw new RuntimeException(e);
        }
    }

    public static <T> T parseObject(String jsonStr, Class<T> t) {
        if (CoreUtil.isBlank(jsonStr)) {
            return null;
        }
        ObjectMapper mapper = new ObjectMapper();
        parseConfig(mapper);
        try {
            return mapper.readValue(jsonStr, t);
        } catch (IOException e) {
            logger.error("反序列化json出错", e);
            throw new RuntimeException(e);
        }
    }

    private static void parseConfig(ObjectMapper mapper) {
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    public static <T> List<T> parseArray(String jsonStr, Class<T> t) {
        if (jsonStr == null) {
            return null;
        }
        if (CoreUtil.isBlank(jsonStr)) {
            return new ArrayList<>();
        }
        ObjectMapper mapper = new ObjectMapper();
        parseConfig(mapper);
        JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, t);
        try {
            return mapper.readValue(jsonStr, javaType);
        } catch (IOException e) {
            logger.error("反序列化json出错,json:" + jsonStr, e);
            throw new RuntimeException(e);
        }
    }

}
